Page({
    data: {
      keyword: '',          // 搜索关键词
      isSearching: false,   // 是否处于搜索状态
      categories: [],       // 分类数据
      recipes: [],          // 推荐菜谱数据
      searchResults: [],    // 搜索结果
      page: 1,              // 当前页码
      pageSize: 6,          // 每页条数
      total: 0,             // 总数据条数
      isLoading: false,     // 加载状态
      loadError: false,     // 加载错误状态
      isEmptyList: false    // 列表是否为空
    },
  
    onLoad() {
      const token = wx.getStorageSync('token'); 
      if (token) {
        this.fetchCategories(token);
        this.fetchRecipes(token);
      } else {
        wx.navigateTo({ url: '/pages/login/index' });
      }
    },
  
    // 获取分类数据
    fetchCategories(token) {
      wx.request({
        url: 'http://localhost:8080/course/categories/list',
        method: 'GET',
        header: { 'Authorization': 'Bearer ' + token },
        success: (res) => {
          if (res.data.code === 200) {
            const newCategories = res.data.rows
              .filter(item => item.id)
              .map(item => ({
                id: Number(item.id),
                name: item.categoryName || '未命名分类'
              }));
            this.setData({ categories: newCategories });
          } else if (res.data.code === 401) {
            wx.navigateTo({ url: '/pages/login/index' });
          }
        },
        fail: (err) => {
          console.error('分类数据请求失败', err);
        }
      });
    },
  
    // 获取推荐菜谱数据（关键修改：提取users.nickname）
    fetchRecipes(token) {
      this.setData({ isLoading: true, loadError: false });
      wx.request({
        url: 'http://localhost:8080/course/courses/Host',
        method: 'GET',
        header: { 'Authorization': token },
        data: {
          page: this.data.page,
          pageSize: this.data.pageSize
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            // 适配数据：从item.users.nickname提取作者名
            const adaptedData = res.data.rows.map((item) => ({
              id: item.id,
              title: item.title || '未知菜谱',
              imgUrl: this.getCoverImage(item.images),
              // 核心：从users对象中获取nickname，默认显示“匿名作者”
              author: item.users?.nickname || '匿名作者', 
              views: item.participantCount || 0,
              score: item.score || 0
            }));
  
            this.setData({
              recipes: adaptedData,
              total: res.data.total,
              isLoading: false,
              isEmptyList: adaptedData.length === 0
            });
          } else {
            this.setData({ 
              loadError: true, 
              isLoading: false,
              isEmptyList: true
            });
            console.error('推荐菜谱接口异常：', res);
          }
        },
        fail: (err) => {
          this.setData({ 
            loadError: true, 
            isLoading: false,
            isEmptyList: true
          });
          console.error('推荐菜谱接口请求失败：', err);
        }
      });
    },
  
    // 提取封面图逻辑
    getCoverImage(images) {
      const defaultImg = '/images/default-recipe.png';
      if (!images || !Array.isArray(images) || images.length === 0) {
        return defaultImg;
      }
  
      const coverImage = images.find(img => img?.description?.includes('封面图'));
      if (coverImage && coverImage.imgUrl) {
        return coverImage.imgUrl.startsWith('http') 
          ? coverImage.imgUrl 
          : `https://gzq123.oss-cn-beijing.aliyuncs.com/${coverImage.imgUrl}`;
      }
  
      const firstImg = images[0] || {};
      return firstImg.imgUrl 
        ? (firstImg.imgUrl.startsWith('http') ? firstImg.imgUrl : `https://gzq123.oss-cn-beijing.aliyuncs.com/${firstImg.imgUrl}`)
        : defaultImg;
    },
  
    // 搜索输入事件（支持按作者名搜索）
    onInput(e) {
      const keyword = e.detail.value.trim();
      let searchResults = [];
      if (keyword) {
        // 过滤条件：标题或作者名包含关键词（不区分大小写）
        searchResults = this.data.recipes.filter(recipe => 
          recipe.title.toLowerCase().includes(keyword.toLowerCase()) || 
          recipe.author.toLowerCase().includes(keyword.toLowerCase())
        );
      }
      this.setData({ 
        keyword,
        searchResults,
        isSearching: !!keyword,
        isEmptyList: keyword ? searchResults.length === 0 : this.data.recipes.length === 0
      });
    },
  
    // 确认搜索事件
    onSearchConfirm(e) {
      const keyword = e.detail.value.trim();
      let searchResults = [];
      if (keyword) {
        searchResults = this.data.recipes.filter(recipe => 
          recipe.title.toLowerCase().includes(keyword.toLowerCase()) || 
          recipe.author.toLowerCase().includes(keyword.toLowerCase())
        );
      }
      this.setData({ 
        keyword,
        searchResults,
        isSearching: !!keyword,
        isEmptyList: keyword ? searchResults.length === 0 : this.data.recipes.length === 0
      });
      this.blurInput();
    },
  
    // 清空关键词
    clearKeyword() {
      this.setData({ 
        keyword: '', 
        searchResults: [], 
        isSearching: false,
        isEmptyList: this.data.recipes.length === 0
      });
      this.blurInput();
    },
  
    onFocus() {
      if (this.data.keyword) {
        this.setData({ isSearching: true });
      }
    },
  
    onBlur() {
      if (!this.data.keyword) {
        this.setData({ isSearching: false });
      }
    },
  
    blurInput() {
      const input = this.selectComponent('.search-input');
      if (input) input.blur();
    },
  
    onCategoryTap(e) {
      const categoryId = e.currentTarget.dataset.id;
      const categoryName = e.currentTarget.dataset.name;
      
      if (!categoryId || isNaN(Number(categoryId))) {
        wx.showToast({ title: '无效的分类', icon: 'none' });
        return;
      }
      
      wx.navigateTo({ 
        url: `/video/pages/hotRecipes/hotRecipes?id=${categoryId}&categoryId=${categoryId}&categoryName=${encodeURIComponent(categoryName || '')}`
      });
    },
  
    goToDetail(e) {
      const recipeId = e.currentTarget.dataset.id;
      if (recipeId) {
        wx.navigateTo({ 
          url: `/video/pages/recipesDetails/recipesDetails?id=${recipeId}` 
        });
      }
    }
  });